<?php

use app\admin\controller\Uploadpdf;
use app\common\controller\Jwt;
use think\Db;


// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function getToken($name, $id)
{
    $jwt = new Jwt();

    //自己使用测试begin
    $payload_test = array('iss' => 'admin', 'iat' => time(), 'exp' => time() + 86400, 'nbf' => time(), 'name' =>
    $name, "id" => $id, 'jti' => md5(uniqid('JWT') . time()));;
    $token_test = Jwt::getToken($payload_test);
    return $token_test;
}

function customSort($a, $b)
{
    $prefixA = substr($a, 0, 3);
    $prefixB = substr($b, 0, 3);
    $suffixA = substr($a, 3, 5);
    $suffixB = substr($b, 3, 5);

    if ($prefixA == $prefixB) {
        return strcmp($suffixA, $suffixB);
    }

    return strcmp($prefixA, $prefixB);
}


function verifyToken($token)
{

    $jwt = new Jwt();
    //对token进行验证签名
    $getPayload_test = Jwt::verifyToken($token);

    return $getPayload_test;
}

/*
 * 目标区域获取的数据
 */

function targetArea($content, $targetAreaTypeRegular)
{


    if (empty($targetAreaTypeRegular)) {
        return array("code" => 400, "data" => "", "message" => "没有填写正则表达式");
    }


    $string = $content;
    $pattern = $targetAreaTypeRegular;


    try {
        preg_match($pattern, $string, $matches);
        // 这里放置可能抛出异常的代码

    } catch (Exception $e) { // 捕获异常

        return array("code" => 400, "data" => "", "message" => $e->getMessage());
    }


    if (empty($matches[0])) {
        return array("code" => 200, "data" => "", "message" => "");
    }

    if (empty($matches[1])) {
        return array("code" => 400, "data" => array(), "message" => "空数据");
    }


    return array("code" => 200, "data" => $matches[1], "message" => "");
}

function multipleTargetArea($content, $pattern)
{

    if (empty($pattern)) {
        return array("code" => 400, "data" => "", "message" => "没有填写正则表达式");
    }

    try {


        preg_match_all($pattern, $content, $matches);

        //        var_dump($pattern);
        //        var_dump($content);
        //        var_dump($matches);

        // 这里放置可能抛出异常的代码
    } catch (Exception $e) { // 捕获异常

        return array("code" => 400, "data" => "", "message" => $e->getMessage());
    }


    if (empty($matches[1])) {
        return array("code" => 200, "data" => array(), "message" => "");
    }


    return array("code" => 200, "data" => $matches[1], "message" => "");
}


function automaticParagraphWrappingSplicing($text)
{
    if (empty($text)) {
        return $text;
    }

    // 将文本按换行符分割成多个段落
    $paragraphs = explode("\n", $text);

    // 用于存储处理后的段落
    $processedParagraphs = [];

    foreach ($paragraphs as $index => $paragraph) {
        // 检查当前段落是否以标点符号结尾
        $isPunctuation = preg_match('/\p{P}$/u', $paragraph);

        // 计算当前段落的字数
        $paragraphLength = mb_strlen($paragraph, 'UTF-8');

        // 如果当前段落不以标点符号结尾，并且段落长度大于30个汉字
        if (!$isPunctuation && $paragraphLength > 20) {
            // 去掉该段落后的换行符
            if ($index < count($paragraphs) - 1) {
                // 如果不是最后一个段落，去掉换行符
                $processedParagraphs[] = $paragraph;
            } else {
                // 如果是最后一个段落，保留原样
                $processedParagraphs[] = $paragraph . "\n";
            }
        } else {
            // 如果当前段落以标点符号结尾或长度小于等于30个汉字，保留原样
            $processedParagraphs[] = $paragraph . "\n";
        }
    }

    // 将处理后的段落重新组合成一个字符串
    $result = implode("", $processedParagraphs);

    return rtrim($result, "\n"); // 去掉最后多余的换行符
}

function automaticParagraphWrappingSplicing1($text)
{

    if (empty($text)) {
        return $text;
    }

    $data = explode("\n", $text);

    // 初始化一个空数组来存储合并后的段落
    $mergedData = [];
    $multi = 0;
    $fistStatus = 0;
    if (count($data) > 0) {
        $firstData = $data[0];
        $fistStatus = preg_match('/\p{P}$/u', $firstData);
        $mergedData[$multi][] = $firstData;
    }
    unset($data[0]);
    // 遍历分割后的段落数组
    foreach ($data as $paragraph) {
        // 检查上一个段落是否已经添加到合并数组中（避免第一个段落前的空检查）

        if ($fistStatus == 1) {
            $multi++;
            $mergedData[$multi][] = $paragraph;
        } else {

            $mergedData[$multi][] = $paragraph;
        }

        $fistStatus = preg_match('/\p{P}$/u', $paragraph);
    }

    $newData = array();
    foreach ($mergedData as $key => $value) {
        $str = implode("", $value);
        $newData[] = $str;
    }


    $str = implode("\n", $newData);

    return $str;
}


function mb_str_split($str, $length = 1)
{
    $result = [];
    for ($i = 0; $i < mb_strlen($str); $i += $length) {
        $result[] = mb_substr($str, $i, $length);
    }
    return $result;
}


function curl_get($resutl)
{

    $kgDomainName = config("kgFilePath");

    $pdf_path = $resutl['pdf_path'];

    $suffixArr = explode(".", $pdf_path);

    //$suffixArr 获取他最后的数组
    $suffix = $suffixArr[count($suffixArr) - 1];

    $url = $kgDomainName . "/{$resutl['kg_id']}/{$resutl['ocr_addre']}_ocr_all.json";


    //        $token = $Uploadpdf->getToken();

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');


    $headers = array();
    $headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7';
    $headers[] = 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6';
    $headers[] = 'Cache-Control: max-age=0';
    $headers[] = 'Connection: keep-alive';
    //        $headers[] = 'Cookie: token= ' . $token;
    //        $headers[] = 'If-Modified-Since: Fri, 06 Sep 2024 07:18:13 GMT';
    //        $headers[] = 'If-None-Match: \"050525694cdd5cf0232fc92fcd3bae23\"';
    $headers[] = 'Sec-Fetch-Dest: document';
    $headers[] = 'Sec-Fetch-Mode: navigate';
    $headers[] = 'Sec-Fetch-Site: none';
    $headers[] = 'Sec-Fetch-User: ?1';
    $headers[] = 'Upgrade-Insecure-Requests: 1';
    $headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0';
    $headers[] = 'Sec-Ch-Ua: \"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Microsoft Edge\";v=\"128\"';
    $headers[] = 'Sec-Ch-Ua-Mobile: ?0';
    $headers[] = 'Sec-Ch-Ua-Platform: \"macOS\"';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $res = curl_exec($ch);


    $info = curl_getinfo($ch);

    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);


        return array("status" => false, "text" => $res);
    }


    curl_close($ch);

    if ($info['http_code'] == 200) {
        return array("status" => true, "text" => $res);
    } else {


        return array("status" => false, "text" => $res);
    }
}

function extractText($jsonData)
{
    $output = "";
    foreach ($jsonData['node'] as $node) {
        foreach ($node['content'] as $content) {
            $output .= $content['str'];
        }
    }
    return $output;
}

function formatText($text)
{
    $text = preg_replace('/\s+/', ' ', $text);
    $text = wordwrap($text, 1584, "\n", true);
    $paragraphs = explode('。', $text);
    $formattedText = "";
    foreach ($paragraphs as $paragraph) {
        if (trim($paragraph) !== "") {
            $formattedText .= trim($paragraph) . "。\n\n";
        }
    }
    return $formattedText;
}


function processText($text, $threshold = 0.2)
{
    // 计算文本中的 \n 数量
    $newlines = substr_count($text, "\n");
    // 计算文本总长度（不包含 \n）
    $textLengthWithoutNewlines = strlen(str_replace("\n", "", $text));
    // 计算 \n 的比例
    $newlineRatio = $newlines / $textLengthWithoutNewlines;

    // 如果 \n 的比例超过阈值，则删除所有 \n
    if ($newlineRatio >= $threshold) {
        $text = str_replace("\n", "", $text);
    }

    // 在所有句号或分号后面加上 \n
    $text = preg_replace_callback('/([.;])/', function ($matches) {
        return $matches[1] . "\n";
    }, $text);

    return $text;
}


function neo4j_connect($dh)
{
    // 设置 Neo4j 的 URL 和认证信息
    $ip = config("neo4j.host");
    $username = config("neo4j.username");
    $password = config("neo4j.password");
    $url = $ip . '/db/gckj/tx';

    // 创建 cURL 会话
    $ch = curl_init();

    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode("$username:$password")
    ]);


    //    $dh = "NJ02-Y-WS-W1955-005-001";

    $data = json_encode([
        "statements" => [
            [
                "statement" => "MATCH (n:`Junqu1.Chunk` {name: '$dh'})-[r*1..2]-(m) UNWIND r AS rel RETURN DISTINCT type(rel), startNode(rel).name, endNode(rel).name   "
            ]
        ]
    ]);


    //    var_dump($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


    // 执行 cURL 会话
    $response = curl_exec($ch);

    // 检查是否有错误
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }

    // 关闭 cURL 会话
    curl_close($ch);

    return $response;
}

function neo4j_connect_raceability($dh) {}

function neo4j_connect_entity($dh, $graphDatabase)
{

    // 设置 Neo4j 的 URL 和认证信息
    $ip = config("neo4j.host");


    $username = config("neo4j.username");
    $password = config("neo4j.password");
    $url = $ip . '/db/' . $graphDatabase . '/tx';

    // 创建 cURL 会话
    $ch = curl_init();

    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Basic ' . base64_encode("$username:$password")
    ]);


    //   $dh = "NJ02-Y-WS-W1955-005-001";

    $data = json_encode([
        "statements" => [
            [
                "statement" => $dh
            ]
        ]
    ]);

    //    var_dump($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


    // 执行 cURL 会话
    $response = curl_exec($ch);

    // 检查是否有错误
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }

    // 关闭 cURL 会话
    curl_close($ch);
    return $response;
}


function getRandomColorName()
{
    $colors = [
        'AliceBlue',
        'Aqua',
        'Aquamarine',
        'Azure',
        'Beige',
        'BlanchedAlmond',
        'Cornsilk',
        'Cyan',
        'DodgerBlue',
        'FloralWhite',
        'GhostWhite',
        'Gold',
        'Gainsboro',
        'HoneyDew',
        'Ivory',
        'Lavender',
        'LavenderBlush',
        'LawnGreen',
        'LemonChiffon',
        'LightBlue',
        'LightCoral',
        'LightCyan',
        'LightGoldenRodYellow',
        'LightGray',
        'LightGreen',
        'LightPink',
        'LightSalmon',
        'LightSeaGreen',
        'LightSkyBlue',
        'LightSlateGray',
        'LightSteelBlue',
        'LightYellow',
        'Lime',
        'Linen',
        'Magenta', // Magenta can be considered light or dark depending on the shade.
        'MintCream',
        'MistyRose',
        'NavajoWhite',
        'OldLace',
        'Orange',
        'PaleGoldenRod',
        'PaleGreen',
        'PaleTurquoise',
        'PapayaWhip',
        'PeachPuff',
        'Peru',
        'Pink',
        'Plum',
        'PowderBlue',
        'Red', // Red can also be light or dark, but often is associated with bright colors.
        'RosyBrown',
        'SandyBrown',
        'SeaShell',
        'SkyBlue',
        'Snow',
        'SpringGreen',
        'SteelBlue',
        'Tan',
        'Thistle',
        'Tomato',
        'Turquoise',
        'Violet',
        'Wheat',
        'White',
        'WhiteSmoke',
        'Yellow'
    ];
    return $colors[array_rand($colors)];
}

function getUserSvg()
{


    return "path://M540.458667 58.794667a426.666667 426.666667 0 1 0 426.666666 426.666666 426.666667 426.666667 0 0 0-426.666666-426.666666z m-248.917334 693.333333a248.917333 248.917333 0 0 1 248.917334-248.917333A142.208 142.208 0 1 1 682.666667 361.002667a142.208 142.208 0 0 1-142.208 142.208A248.917333 248.917333 0 0 1 789.333333 752.128H291.541333z";
}

function getOrderSvg()
{
    return "path://M513.740997 479.317978a139.219776 139.219776 0 0 1-139.219775-135.297782 915.058526 915.058526 0 0 1-298.26552-99.78484v746.861797a33.115947 33.115947 0 0 0 33.552946 32.898947h804.379704a33.333946 33.333946 0 0 0 33.552946-32.898947v-750.348791a903.293544 903.293544 0 0 1-294.562525 105.66783 137.912778 137.912778 0 0 1-139.437776 132.901786z m35.295943 381.710385h-312.209497v-45.099928h312.209497z m81.265869-114.164816H236.827443V703.289617h393.475366z m160.570742-115.035815H236.827443v-43.57393h554.046108v43.57393zM914.188352 0.00175H109.808648a33.333946 33.333946 0 0 0-33.552946 32.897947v149.02376A920.941516 920.941516 0 0 0 383.236207 292.820278a140.090774 140.090774 0 0 1 257.524586 0 830.524662 830.524662 0 0 0 305.019508-116.125813V32.900697A31.590949 31.590949 0 0 0 914.188352 0.00175z";
}


function getShopSvg()
{
    return "path://M380.830476 628.662857h-133.607619a8.43581 8.43581 0 0 0-8.289524 8.582095v138.752a8.777143 8.777143 0 0 0 2.267429 6.38781c1.560381 1.706667 3.730286 2.681905 6.022095 2.681905h133.607619c4.583619 0 8.289524-3.85219 8.289524-8.582096v-139.215238a8.752762 8.752762 0 0 0-2.438095-6.095238 8.118857 8.118857 0 0 0-5.851429-2.511238z m211.431619 0h-133.217524a8.655238 8.655238 0 0 0-8.484571 8.630857v139.166476c0.121905 4.778667 3.900952 8.606476 8.484571 8.606477h133.217524a8.655238 8.655238 0 0 0 8.484572-8.606477v-139.166476a8.655238 8.655238 0 0 0-8.484572-8.630857z m211.626667 0h-133.217524a8.655238 8.655238 0 0 0-8.484571 8.630857v139.166476c0.121905 4.778667 3.900952 8.606476 8.484571 8.606477h133.217524a8.655238 8.655238 0 0 0 8.484571-8.606477v-139.166476a8.655238 8.655238 0 0 0-8.484571-8.630857zM634.977524 211.626667h-218.648381c-7.192381 0-13.55581 4.559238-13.55581 10.288762v166.131809c0 5.705143 6.095238 10.288762 13.55581 10.288762h218.648381c7.460571 0 13.55581-4.583619 13.555809-10.288762V221.915429c0-5.729524-6.095238-10.288762-13.555809-10.288762z m87.137524 400.091428v-93.817905h-178.151619v93.574096h-35.644953v-93.574096h-179.126857v93.793524H293.546667v-117.394285h213.820952v-82.651429h36.254476v82.651429h214.137905v117.394285h-35.644952z";
}

function getFlagSvg()
{
    return "path://M226.133 34.133c-18.88 0-34.133 15.254-34.133 34.134v887.466c0 18.88 15.253 34.134 34.133 34.134s34.134-15.254 34.134-34.134V68.267c0-18.88-15.254-34.134-34.134-34.134z m602.24 312.427L380.8 66.773c-22.72-14.186-52.267 2.134-52.267 28.907v559.467c0 26.773 29.44 43.2 52.267 28.906l447.573-279.786c21.334-13.227 21.334-44.374 0-57.707z";
}

function getDateSvg()
{
    return "path://M512 78c239.692 0 434 194.308 434 434S751.692 946 512 946 78 751.692 78 512 272.308 78 512 78z m-3.15 196c-20.352 0-36.85 16.498-36.85 36.85v202.429a29.394 29.394 0 0 0 8.842 21.01l152.252 148.966c14.54 14.227 37.854 13.995 52.11-0.518l0.05-0.051c14.19-14.504 13.937-37.766-0.567-51.957L549.015 497.985a11.023 11.023 0 0 1-3.316-7.878V310.85c0-20.352-16.498-36.85-36.85-36.85z";
}

function getGeographicLocationSvg()
{
    return "path://M512 78c239.692 0 434 194.308 434 434S751.692 946 512 946 78 751.692 78 512 272.308 78 512 78zM363.093 323.093c-81.963 81.964-82.783 214.343-2.459 297.315l2.46 2.499 141.42 141.421c4.609 4.608 12.033 4.685 16.735 0.23l0.236-0.23 141.422-141.421c82.79-82.792 82.79-217.022 0-299.814-82.792-82.79-217.022-82.79-299.814 0zM512 354c65.17 0 118 52.83 118 118s-52.83 118-118 118-118-52.83-118-118 52.83-118 118-118z m0 56c-34.242 0-62 27.758-62 62 0 34.242 27.758 62 62 62 34.242 0 62-27.758 62-62 0-34.242-27.758-62-62-62z";
}


function getJson($content)
{
    $substring = mb_substr($content, 0, 7);

    if ($substring == "```json") {
        preg_match('/```json\s*({.*?})\s*```/s', $content, $matches);

        return $matches[1];
    }

    return $content;
}

function checkFields($str)
{

    if ($str == "无"  || $str == "none" || $str == "unknown" || $str == "未知"  || empty($str)) {
        return false;
    }

    return true;
}


function getImageJpg($imagePath)
{
    if (pathinfo($imagePath, PATHINFO_EXTENSION) == 'tif') {
        $image  = tifToJpg($imagePath);
        // 检查转换是否成功
        if (!$image  || !file_exists($image)) {
            error_log("TIF转JPG失败");
            return null;
        }
        return $image;
    }
    return $imagePath;
}

/**
 * TIF格式转JPG格式
 * @param string $tifPath TIF图片路径
 * @return string 转换后的JPG图片路径
 */
function tifToJpg($tifPath)
{
    // 检查文件是否存在
    if (!file_exists($tifPath)) {
        error_log("文件不存在: $tifPath");
        return null;
    }

    try {
        // 使用Imagick转换格式
        $image = new \Imagick($tifPath);
        $image->setImageFormat('jpg');

        // 创建临时文件保存转换结果
        $jpgPath = tempnam(sys_get_temp_dir(), 'tif_converted_') . '.jpg';
        $image->writeImage($jpgPath);

        // 释放资源
        $image->clear();
        $image->destroy();

        return $jpgPath;
    } catch (\Exception $e) {
        error_log("转换图片出错: " . $e->getMessage());
        return null; // 转换失败返回null
    }
}


function getUniqueString($id, $type = 1){
// 保存为 PDF 文件
        $pdPath = config("path") . "pdf/data/{$id}/";
        // 检查目录是否存在
        if (!file_exists($pdPath)) {
            // 目录不存在，尝试创建
            mkdir($pdPath, 0777, true);
        }

        $str = md5($id);

        if ($type == 1) {
            $pdPath = $pdPath . "{$str}_monolayer.pdf";
        }

        if ($type == 2) {
            $pdPath = $pdPath . "{$str}_double.pdf";
        }

        if ($type == 3) {
            $pdPath = $pdPath . "{$str}_data.json";
        }


        return $pdPath;
    }


    function getMonolayerName($id){
        $str = md5($id)."_monolayer.pdf";
        return  $str ;
    }
